package org.vincen.helloworld.mybatis;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DAOManager {
	
	private SqlSessionFactory factoryBuilder () throws IOException {
		String fileDirectory = "com/vincen/mybatis/SqlMapConfig.xml";
		Reader reader = Resources.getResourceAsReader(fileDirectory);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
		return factory;
	}
	
	@SuppressWarnings("unused")
	private void userDaoTest1 () throws IOException {
		SqlSessionFactory factory = this.factoryBuilder();
		
		SqlSession session = factory.openSession();
		UserDao userDao = session.getMapper(UserDao.class);
		User user = new User();
		user.setName("vincen");
		user.setPassword("vincen");
		userDao.insert(user);
		session.commit();
		session.close();
	}
	
	private void userDaoTest2 () throws IOException {
		SqlSessionFactory factory = this.factoryBuilder();
		SqlSession session = factory.openSession();
		UserDao userDao = session.getMapper(UserDao.class);
		System.out.println(userDao.countUser());
		List<User> users = userDao.selectAll();
		for (User u : users) {
			System.out.println(u.getId() + ", " + u.getName() + ", " + u.getPassword());
		}
		session.commit();
		session.close();
	}

	public static void main(String[] args) {
		DAOManager dm = new DAOManager();
		try {
//			dm.userDaoTest1();
			dm.userDaoTest2();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
